﻿import QtQuick 2.0
import QtQuick.Templates 2.12

Item {
    id: root
    readonly property real dp: config.dp

    property string box_text: "CustomCheckBox"
    property int box_size: 18 * dp

    property color fontColor: "#444444"
    property string box_color: fontColor

    property bool check: false
    property bool checkable: true

    // 定义一个信号，当复选框状态改变时发射这个信号，携带当前的选中状态作为参数
    signal statusChanged(bool newStatus)

    function getStatus() {
        return check
    }

    height: 40 * dp
    width: 100 * dp

    Rectangle {
        height: box_size
        width: box_size
        x: 3 * dp
        radius: 3 * dp
        anchors.verticalCenter: root.verticalCenter
        border.color: "#AAAAAA"
        Rectangle {          // 选择Rect样式
            height: box_size - 0 * dp
            width: box_size - 0 * dp
            radius: 3 * dp
            x: 0 * dp
            y: 0 * dp
            color: box_color
            visible: check
            Text {
                text: "✔"
                color: "white"
                anchors.centerIn: parent
                font.pixelSize: config.fontsize - 4
                opacity: 1
            }
            opacity: 0.9
        }
        Rectangle {          // 不可选时的样式
            height: box_size - 0 * dp
            width: box_size - 0 * dp
            color: "#EEEEEE"
            visible:!checkable
        }

        MouseArea {
            anchors.fill: parent
            cursorShape: Qt.PointingHandCursor
            onReleased: {
                root.focus = true
                if (checkable) {
                    check =!check
                    // 当状态改变时，发射statusChanged信号，并传递当前的选中状态
                    statusChanged(check)
                }
            }
        }
    }

    Item {               // 文本
        height: root.height
        x: box_size + 10 * dp
        width: box_text.length * (config.fontsize - 2 * dp)
        Text {
            text: qsTr(box_text)
            font.pixelSize: config.fontsize
            color: checkable? fontColor : "#AAAAAA"
            anchors.verticalCenter: parent.verticalCenter
        }
        MouseArea {
            height: 20 * dp;
            width: parent.width
            x: -10 * dp;
            y: 10 * dp
            cursorShape: Qt.PointingHandCursor
            onReleased: {
                root.focus = true
                if (checkable) {
                    check =!check
                    // 当状态改变时，发射statusChanged信号，并传递当前的选中状态
                    statusChanged(check)
                }
            }
        }
    }
}
